<template>
    <div class="module-page" v-loading="loading">
        <el-form :model="taskInfo" :rules="rules" ref="taskInfo" label-width="120px" class="demo-taskInfo">
            <el-form-item label="网络选择" prop="name">
                <el-radio-group :disabled="!!taskId" v-model="taskInfo.network" @change="resetData" size="small" class="left-btn">
                    <el-radio-button v-for="item in networks" :label="item.value" :key="item.value">{{ item.label }}</el-radio-button>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="任务名称" prop="taskName">
                <el-input :maxlength="100" show-word-limit :disabled="!!taskId" v-model="taskInfo.taskName"></el-input>
            </el-form-item>
            <el-form-item label="评估模板" prop="modelId">
                <el-select :disabled="!!taskId" style="width: 100%" v-model="taskInfo.modelId" @change="getDeviceList" placeholder="请选择分析模板">
                    <el-option v-for="item in modelList" :key="item.id" :label="item.modelName" :value="item.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item v-if="!taskId" label="区域" prop="resourceGroupName">
                <el-select :disabled="!!taskId" style="width: 100%" v-model="taskInfo.resourceGroupName" @change="groupNameChange" placeholder="请选择区域">
                    <el-option v-for="item in groupList" :key="item.groupId" :label="item.groupName" :value="item.groupName"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item v-if="taskInfo.modelId && taskInfo.resourceGroupName" label="设备" prop="code">
                <el-select :disabled="!!taskId" filterable style="width: 100%" v-model="taskInfo.code" placeholder="请选择分析设备">
                    <el-option v-for="item in deviceTypeSelectList" :key="item.code" :label="item.name" :value="item.code"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="巡检周期" prop="desc">
                <el-radio-group :disabled="!!taskId" v-model="taskInfo.cycleType" class="left-btn">
                    <el-radio-button :label="1">一次</el-radio-button>
                    <el-radio-button :label="2">每天</el-radio-button>
                    <el-radio-button :label="3">每周</el-radio-button>
                    <el-radio-button :label="4">每月</el-radio-button>
<!--                    <el-radio-button label="5">分钟（测试用）</el-radio-button>-->
                </el-radio-group>
            </el-form-item>
            <el-form-item v-if="taskInfo.cycleType !== 1" label="执行时间" prop="desc">
                <div class="flex-row flex-item">
                    <template v-if="taskInfo.cycleType === 3 && taskInfo.weekday">
                        <el-select size="small"
                                   style="width: 100px"
                                   :disabled="!!taskId"
                                   v-model="taskInfo.weekday"
                                   placeholder="星期">
                            <el-option
                                    v-for="item in weekdays"
                                    :key="item.value"
                                    :label="item.name"
                                    :value="item.value">
                            </el-option>
                        </el-select>
                    </template>
                    <template v-if="taskInfo.cycleType === 4 && taskInfo.dateNum">
                        <el-select size="small"
                                   style="width: 100px"
                                   :disabled="!!taskId"
                                   v-model="taskInfo.dateNum"
                                   placeholder="日期">
                            <el-option
                                    v-for="i in 31"
                                    :key="i"
                                    :label="`${i}`"
                                    :value="`${i}`">
                            </el-option>
                        </el-select>
                        <span class="time-unit">号</span>
                    </template>
                    <el-select size="small"
                               style="width: 100px"
                               :disabled="!!taskId"
                               v-model="taskInfo.hours"
                               placeholder="小时">
                        <el-option
                                v-for="i in 24"
                                :key="i - 1"
                                :label="`${i - 1}`"
                                :value="`${i - 1}`">
                        </el-option>
                    </el-select>
                    <span class="time-unit">时</span>
                    <el-select size="small"
                               v-if="taskInfo.cycleType !== 1"
                               style="width: 100px"
                               :disabled="!!taskId"
                               v-model="taskInfo.minutes"
                               placeholder="分钟">
                        <el-option
                                v-for="i in 60"
                                :key="i - 1"
                                :label="`${i - 1}`"
                                :value="`${i - 1}`">
                        </el-option>
                    </el-select>
                    <span v-if="taskInfo.cycleType !== 1" class="time-unit">分</span>
                </div>
            </el-form-item>
            <el-form-item>
                <el-button size="small" v-if="!taskId" @click="close(false)">取消</el-button>
                <el-button size="small" v-if="!taskId" type="primary" @click="submitForm">确定</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
import { networks } from '@/assets/dict'
import moment from 'moment'
export default {
  name: 'taskInfo',
  data() {
    return {
      weekdays: [
        { name: '星期一', value: 'MON' },
        { name: '星期二', value: 'TUE' },
        { name: '星期三', value: 'WED' },
        { name: '星期四', value: 'THU' },
        { name: '星期五', value: 'FRI' },
        { name: '星期六', value: 'SAT' },
        { name: '星期天', value: 'SUN' }
      ],
      networks,
      taskInfo: {
        cycleType: 1,
        network: 'JZW',
        modelId: '',
        code: '',
        taskName: '',
        dateNum: '1',
        hours: '1',
        minutes: '1',
        weekday: 'MON',
        resourceGroupName: ''
      },
      rules: {
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        modelId: [
          { required: true, message: '请选择评估模板', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请选择设备' }
        ],
        resourceGroupName: [
          { required: true, message: '请选择区域' }
        ]
      },
      modelList: [],
      groupList: [],
      deviceTypeList: [],
      taskId: '',
      loading: false
    }
  },
  methods: {
    init(network, taskId) {
      this.taskId = taskId
      this.taskInfo.network = network || 'JZW'
      this.getModelList()
      if (this.taskId) {
        this.queryTaskInfo()
      }
    },
    resetData() {
      this.getModelList()
      this.taskInfo = {
        ...this.taskInfo,
        cycleType: 1,
        modelId: '',
        code: '',
        taskName: '',
        dateNum: '1',
        hours: '1',
        minutes: '1',
        weekday: 'MON',
        resourceGroupName: ''
      }
    },
    groupNameChange() {
      this.taskInfo = {
        ...this.taskInfo,
        cycleType: 1,
        code: '',
        dateNum: '1',
        hours: '1',
        minutes: '1',
        weekday: 'MON'
      }
    },
    queryTaskInfo() {
      this.$http.get('/evaluate/getTaskDetail', {
        params: {
          taskId: this.taskId
        }
      }).then(res => {
        this.getDeviceList(res.modelId)
        const keys = Object.keys(this.taskInfo)
        keys.forEach(key => {
          this.taskInfo[key] = res[key]
        })
        this.taskInfo.createTime = moment(res.createTime).format('YYYY-MM-DD HH:mm:ss')
      })
    },
    getModelList() {
      this.$http.get('/evaluate/getModelList', {
        params: {
          network: this.taskInfo.network,
          pageNum: 1,
          pageSize: 999
        }
      }).then(res => {
        this.modelList = res.records
      }).catch(err => {
        this.$TZmessage.error(err.msg || '获取列表失败')
      })
    },
    getDeviceList(id) {
      const device = this.modelList.find(item => item.id === id) || {}
      console.log(device)
      this.taskInfo.code = ''
      this.$http.get('/device/getDeviceList', {
        params: {
          network: this.taskInfo.network,
          deviceType: device.deviceType,
          deviceTypeTwo: device.deviceTypeTwo,
          pageNum: 1,
          pageSize: 999
        }
      }).then(res => {
        this.deviceTypeList = (res.records || [])
      }).catch(err => {
        this.$TZmessage.error(err.msg || '获取设备列表失败')
      })
    },
    submitForm() {
      this.$refs.taskInfo.validate((valid) => {
        if (valid) {
          this.addTask()
        } else {
          return false;
        }
      });
    },
    addTask() {
      this.loading = true
      this.$http.post('/evaluate/addEvaluateTask', this.taskInfo).then(res => {
        this.$TZmessage.success('新建任务成功')
        this.close(true)
      }).catch(err => {
        this.$TZmessage.error(err.msg || '添加任务失败')
      }).finally(() => {
        this.loading = false
      })
    },
    getGroupsList() {
      this.$http('/sys/user/getGroupList').then(res => {
        this.groupList = res || []
      }).catch(err => {
        this.$TZmessage.error(err.msg || '获取分组数据失败')
      })
    },
    close(refresh) {
      this.$emit('close', refresh)
    }
  },
  mounted() {
    this.getGroupsList()
  },
  computed: {
    deviceArea() {
      const deviceItem = this.deviceTypeList.find(item => (this.taskInfo.code && this.taskInfo.code === item.code))
      if (deviceItem && deviceItem.resourceGroupName) {
        return deviceItem.resourceGroupName.replace(/\[/, '').replace(/\]/, '')
      }
      return ''
    },
    deviceTypeSelectList() {
      return this.deviceTypeList.filter(item => {
        return !this.taskInfo.resourceGroupName || (item.resourceGroupName === this.taskInfo.resourceGroupName)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
    .module-page {
        padding: 27px;
        width: 100%;
        max-width: 600px;
        box-sizing: border-box;
        .time-unit {
            padding: 0 10px;
        }
    }
</style>